const { TeaModel, TeaAndClassModel } = require("../model");
const mongoose = require("mongoose");
/// 以下所有接口等待职位表完成后，再进行优化！！！！！！！！！！！！
//添加教师
exports.addTeacher = async (req, res) => {
  const { teaNumber, teaName, teaSex, teaPassword, jobId } = req.body;
  if (!teaNumber || !teaName || !teaSex || !teaPassword || !jobId) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "参数错误",
    });
  }
  let result = await TeaModel.findOne({ teaNumber });
  if (result) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "该教师已存在",
    });
  }
  try {
    let dbBack = new TeaModel({
      teaName,
      teaNumber,
      teaSex,
      teaPassword,
      jobId,
    });
    await dbBack.save();
    return res.status(200).json({
      code: 200,
      data: null,
      message: "添加成功",
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "添加失败",
    });
  }
};
//获取教师列表
exports.getTeacherList = async (req, res) => {
  const { pageNo = 1, pageSize = 5, keyword = "" } = req.query;
  if (keyword) {
    try {
      let result = await TeaModel.find({ teaNumber: { $regex: keyword } })
        .skip((pageNo - 1) * pageSize)
        .limit(pageSize)
        .populate("jobId", "jobName");
      let count = await TeaModel.find({
        teaNumber: { $regex: keyword },
      }).count();
      for (let i = 0; i < result.length; i++) {
        let classList = await TeaAndClassModel.find({
          teaId: result[i]._id,
        }).populate("classId");
        result[i]._doc.classList = classList.map(
          (item) => item.classId.className
        );
      }
      return res.status(200).json({
        code: 200,
        data: {
          result,
          total: count,
        },
        message: "查询成功",
      });
    } catch (error) {
      return res.status(500).json({
        code: 500,
        data: null,
        message: "查询失败" + error,
      });
    }
  } else {
    try {
      let result = await TeaModel.find()
        .skip((pageNo - 1) * pageSize)
        .limit(pageSize)
        .populate("jobId", "jobName");

      let count = await TeaModel.find().countDocuments(); // 使用 countDocuments 而不是 count

      // 使用 Promise.all 来并行处理异步操作
      let classLists = await Promise.all(
        result.map(async (teaItem) => {
          let TeaClassList = await TeaAndClassModel.find({
            teaId: teaItem._id,
          }).populate("classId");
          return TeaClassList.map((item) => item.classId.className); // 直接返回类名数组
        })
      );

      // 创建一个新的结构来包含所需的数据
      let formattedResult = result.map((teaItem, index) => ({
        ...teaItem._doc, // 如果需要，可以复制其他属性
        classList: classLists[index], // 添加类名列表
      }));

      return res.status(200).json({
        code: 200,
        data: {
          result: formattedResult, // 使用新的 formattedResult
          total: count,
        },
        message: "查询成功",
      });
    } catch (error) {
      return res.status(500).json({
        code: 500,
        data: null,
        message: "查询失败: " + error.message, // 最好只返回错误信息，而不是整个错误对象
      });
    }
  }
};
//获取教师详情
exports.getTeacherDetail = async (req, res) => {
  const { id } = req.query;
  if (!id) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "id不能为空",
    });
  }
  try {
    let result = await TeaModel.findById(id).populate("jobId", "jobName");
    if (!result) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "查询用户不存在",
      });
    }
    let teaClass = await TeaAndClassModel.find({ teaId: id }).populate(
      "classId"
    );
    result._doc.classList = teaClass.map((item) => item.classId.className);
    return res.status(200).json({
      code: 200,
      data: result,
      message: "查询成功",
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "查询失败" + error,
    });
  }
};
//修改教师接口
exports.updateTeacher = async (req, res) => {
  const id = req.query.id;
  const { teaIsWork = 0 } = req.body;
  if (!id) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "id不能为空",
    });
  }

  try {
    await TeaModel.findByIdAndUpdate(id, req.body);
    if (teaIsWork !== 0) {
      await TeaAndClassModel.deleteMany({ teaId: id });
    }
    return res.status(200).json({
      code: 200,
      data: null,
      message: "修改成功",
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "修改失败" + error,
    });
  }
};
//删除教师接口
exports.deleteTeacher = async (req, res) => {
  const id = req.query.id;
  if (!id) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "id不能为空",
    });
  }
  try {
    await TeaModel.findByIdAndDelete(id);
    await TeaAndClassModel.deleteMany({ teaId: id });
    return res.status(200).json({
      code: 200,
      data: null,
      message: "删除成功",
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "删除失败",
    });
  }
};
//给教师分配班级
exports.assignClass = async (req, res) => {
  const { tId, classArr } = req.body;
  if (!tId || !Array.isArray(classArr) || classArr.length === 0) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "参数不能为空",
    });
  }

  try {
    // 检查所有班级是否都已经被其他教师带班
    const existingClasses = await TeaAndClassModel.find({
      classId: { $in: classArr },
      teaId: { $ne: tId }, // 排除当前教师自己带的班级
    });

    if (existingClasses.length > 0) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "部分班级已经被其他教师带班",
      });
    }

    // 删除对应的教师所带班级的记录
    await TeaAndClassModel.deleteMany({ teaId: tId });

    // 批量插入
    const arr = classArr.map((item) => ({ teaId: tId, classId: item }));
    await TeaAndClassModel.insertMany(arr);

    return res.status(200).json({
      code: 200,
      data: arr, // 返回分配给教师的班级列表
      message: "分配成功",
    });
  } catch (error) {
    // 捕获并处理错误
    return res.status(500).json({
      code: 500,
      data: null,
      message: "分配失败", // 不返回具体的错误对象
    });
  }
};
//获取教师所带班级
exports.getTeaAndClass = async (req, res) => {
  const { id } = req.query;
  if (!id) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "教师Id不能为空",
    });
  }
  try {
    let result = await TeaAndClassModel.find({ teaId: id }).populate(
      "classId",
      "className"
    );
    const extractedData = result.map((item) => ({
      _id: item.classId._id, // 提取_id
      className: item.classId.className, // 提取className
    }));
    return res.status(200).json({
      code: 200,
      data: extractedData,
      message: "查询成功"
    })
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "查询失败"
    })
  }
};
